// 注册接口
/* eslint-disable */
<template>
  <div>
    <!-- 吸顶菜单 -->
    <el-affix :offset="0">
      <el-menu
        mode="horizontal"
        background-color="#545c64"
        text-color="#fff"
        active-text-color="#ffd04b"
        style="width: 100vw; display: flex; justify-content: flex-end;"
      >
        <!-- 添加年份选择器 -->
        <el-menu-item style="float: right;">
          <span style="color: #fff; margin-right: 10px;">开始时间</span>
          <el-select v-model="startYear" placeholder="开始年份" style="width: 120px;">
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="year"
              :value="year">
            </el-option>
          </el-select>
        </el-menu-item>
        <el-menu-item style="float: right;">
          <span style="color: #fff; margin-right: 10px;">结束时间</span>
          <el-select v-model="endYear" placeholder="结束年份" style="width: 120px;">
            <el-option
              v-for="year in yearOptions"
              :key="year"
              :label="year"
              :value="year">
            </el-option>
          </el-select>
        </el-menu-item>
        <el-menu-item style="float: right;">
          <span style="color: #fff; margin-right: 10px;">歌曲调式</span>
          <el-select
            v-model="selectedKey"
            placeholder="歌曲调式"
            style="width: 120px;"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :collapse-tags-limit="1"
            @change="handleKeyChange"
          >
            <el-option
              v-for="key in keyOptions"
              :key="key.value"
              :label="key.label"
              :value="key.value"
            >
            </el-option>
          </el-select>
        </el-menu-item>
        <el-menu-item style="float: right;">
          <span style="color: #fff; margin-right: 10px;">歌曲风格</span>
          <el-select
            v-model="selectedStyles"
            placeholder="选择歌曲风格"
            style="width: 200px;"
            multiple
            collapse-tags
            collapse-tags-tooltip
            :collapse-tags-limit="1"
          >

            <el-option
              v-for="style in musicStyles"
              :key="style"
              :label="style"
              :value="style">
            </el-option>
          </el-select>
        </el-menu-item>
        <el-menu-item style="float: right;">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-menu-item>
      </el-menu>
    </el-affix>

    <!-- 页面内容区域 -->
    <div style="display: flex; height: calc(100vh - 60px); margin-top: 60px; flex: 1; justify-content: flex-start;">
      <!-- 左侧内容区域 -->
      <div style="flex: 0.5; padding-right: 20px; display: flex; flex-direction: column; width: 800px; height: 100%; position: relative;">
        <!-- 表格头和内容区域 -->
        <div style="flex: 1; overflow: auto;">
          <!-- 表格头 -->
          <div style="display: flex; padding: 10px; background: #e0e0e0; font-weight: bold; border-bottom: 1px solid #ddd;">
            <div style="width: 60px;">排名</div>
            <div style="flex: 1;">歌名</div>
            <div style="flex: 1;">歌手</div>
            <div style="width: 120px;">流派</div>
            <div style="width: 80px;">流行度</div>
            <div style="width: 80px;">年份</div>
          </div>
          <!-- 分页显示数据 -->
          <div v-for="(item, index) in paginatedData" :key="index" style="padding: 10px; border-bottom: 1px solid #eee; display: flex;">
            <div style="width: 60px;">{{ (currentPage - 1) * pageSize + index + 1 }}</div>
            <div style="flex: 1; cursor: pointer; color: #409eff;" @click="showSongDetail(item)">{{ item.trackName }}</div>
            <div style="flex: 1;">{{ item.artistName[0] }}</div>
            <div style="width: 120px;">{{ item.genre }}</div>
            <div style="width: 80px;">{{ item.popularity }}</div>
            <div style="width: 80px;">{{ item.year }}</div>
          </div>
        </div>
        <!-- 固定在底部的分页 -->
        <div style="position: sticky; bottom: 0; background: #f5f5f5; padding: 10px 0;">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
      <!-- 右侧内容区域 (占2份) -->
      <div style="flex: 0.5;  display: flex; flex-direction: column; height: 100%;">
        <!-- 上半部分 -->
        <div style="flex: 2; overflow: auto; border-bottom: 1px solid #ddd; display: flex;">
          <!-- 左半部分 - 歌曲调式分布 -->
          <div style="flex: 0.5; padding: 10px; border-right: 1px solid #ddd;">
            <div id="key-pie-chart" style="width: 400px; height: 100%;"></div>
          </div>
          <!-- 右半部分 - 歌曲流派分布 -->
          <div style="flex: 0.5; padding: 10px;">
            <div id="style-pie-chart" style="width: 400px; height: 100%;"></div>
          </div>
        </div>
        <!-- 下半部分 -->
        <div style="flex: 3; display: flex; flex-direction: column;">
          <!-- 上半部分 -->
          <div style="flex: 1; overflow: auto; border-bottom: 1px solid #ddd;">
            <div id="danceability-chart" style="width: 100%; height: 100%;"></div>
          </div>
          <!-- 下半部分 -->
          <div style="flex: 1; overflow: auto;">
            <div id="energy-chart" style="width: 100%; height: 100%;"></div>
          </div>
        </div>
      </div>
    </div>
    <!-- 页面其他内容 -->
    </div>

    <el-drawer
      v-model="drawerVisible"
      :title="currentSong?.trackName + ' - 歌曲详情'"
      direction="ltr"
      size="30%"
      :modal="false"
      :modal-class="'custom-drawer-modal'"
      custom-class="custom-drawer"
      :wrapperClosable="false"
    >
      <div class="song-detail-container">
        <div class="detail-header">
          <h3>{{ currentSong?.trackName }}</h3>
        </div>
        <div class="detail-row">
          <div class="detail-label">歌手:</div>
          <div class="detail-value">{{ currentSong?.artistName[0] }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">流派:</div>
          <div class="detail-value">{{ currentSong?.genre }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">适合跳舞程度:</div>
          <div class="detail-value">{{ currentSong?.danceability }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">活跃度:</div>
          <div class="detail-value">{{ currentSong?.energy }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">流行度:</div>
          <div class="detail-value" :class="{
            'popular-high': currentSong?.popularity > 70,
            'popular-medium': currentSong?.popularity > 40 && currentSong?.popularity <= 70,
            'popular-low': currentSong?.popularity <= 40
          }">
            {{ currentSong?.popularity }}
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-label">年份:</div>
          <div class="detail-value">{{ currentSong?.year }}</div>
        </div>
      </div>
    </el-drawer>
</template>

<script>
import * as echarts from 'echarts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getList, getGenresList, getDiaoShi, getKeyFenBu, getGenresFenBu, getDanceFenBu, getPowerFenBu } from '@/api/mess' // 添加getGenresFenBu导入

export default {
  computed: {
    paginatedData () {
      return this.tableData
    }
  },
  mounted () {
    this.initKeyPieChart()
    this.initStylePieChart()
    this.initDanceabilityChart()
    this.initEnergyChart()
    this.f()
    this.fetchGenres() // 新增方法调用
    this.fetchDiaoShi() // 新增方法调用
  },
  methods: {
    handleKeyChange (val) {
      this.selectedKey = val
    },
    async initEnergyChart () {
      const chartDom = document.getElementById('energy-chart')
      const myChart = echarts.init(chartDom)
      try {
        const params = {
          start: this.startYear,
          end: this.endYear,
          genres: this.selectedStyles,
          keys: this.selectedKey
        }
        const powerData = await getPowerFenBu(params)
        const option = {
          title: {
            text: '歌曲强度与活跃度分布',
            left: 'center',
            textStyle: {
              fontSize: 13
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: ['0-0.1', '0.1-0.2', '0.2-0.3', '0.3-0.4', '0.4-0.5',
              '0.5-0.6', '0.6-0.7', '0.7-0.8', '0.8-0.9', '0.9-1.0'],
            axisLabel: {
              interval: 0,
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '歌曲数量'
          },
          series: [{
            name: '强度与活跃度',
            type: 'bar',
            barWidth: '80%',
            data: powerData, // 使用API返回的数据
            itemStyle: {
              color: '#F56C6C'
            }
          }]
        }
        myChart.setOption(option)
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      } catch (error) {
        console.error('获取强度与活跃度数据失败:', error)
        ElMessage.error('获取强度与活跃度数据失败')
      }
    },
    async initKeyPieChart () {
      this.isLoading.keyChart = true
      try {
        const chartDom = document.getElementById('key-pie-chart')
        const myChart = echarts.init(chartDom)
        try {
          const params = {
            start: this.startYear,
            end: this.endYear,
            genres: this.selectedStyles,
            keys: this.selectedKey
          }
          const response = await getKeyFenBu(params)
          // 调式名称映射（修改为符合ESLint规范的格式）
          const keyNames = {
            0: 'C',
            1: 'C#',
            2: 'D',
            3: 'D#',
            4: 'E',
            5: 'F',
            6: 'F#',
            7: 'G',
            8: 'G#',
            9: 'A',
            10: 'A#',
            11: 'B'
          }
          // 使用映射后的调式名称
          const chartData = response.map(item => ({
            value: item.num,
            name: keyNames[item.key] || item.key // 如果没有匹配则显示原值
          }))
          console.log('调式分布数据:', chartData)
          const option = {
            title: {
              text: '歌曲调式分布',
              left: 'center',
              textStyle: {
                fontSize: 13
              }
            },
            tooltip: {
              trigger: 'item'
            },
            legend: {
              orient: 'horizontal',
              bottom: 10,
              data: chartData.map(item => item.name)
            },
            series: [
              {
                name: '调式分布',
                type: 'pie',
                radius: '50%',
                data: chartData,
                emphasis: {
                  itemStyle: {
                    shadowBlur: 10,
                    shadowOffsetX: 0,
                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                  }
                }
              }
            ]
          }
          myChart.setOption(option)
          window.addEventListener('resize', function () {
            myChart.resize()
          })
        } catch (error) {
          console.error('获取调式分布数据失败:', error)
          ElMessage.error('获取调式分布数据失败')
        }
      } finally {
        this.isLoading.keyChart = false
      }
    },

    async initStylePieChart () {
      const chartDom = document.getElementById('style-pie-chart')
      const myChart = echarts.init(chartDom)
      try {
        const params = {
          start: this.startYear,
          end: this.endYear,
          genres: this.selectedStyles,
          keys: this.selectedKey
        }
        const response = await getGenresFenBu(params)
        const chartData = response.map(item => ({
          value: item.num,
          name: item.genre
        }))
        const option = {
          title: {
            text: '歌曲流派分布',
            left: 'center',
            textStyle: {
              fontSize: 13
            }
          },
          tooltip: {
            trigger: 'item'
          },
          // 移除了legend配置
          series: [
            {
              name: '流派分布',
              type: 'pie',
              radius: '50%',
              data: chartData,
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
        myChart.setOption(option)
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      } catch (error) {
        console.error('获取流派分布数据失败:', error)
        ElMessage.error('获取流派分布数据失败')
      }
    },
    initBarChart () {
      const chartDom = document.getElementById('bar-chart-container')
      const myChart = echarts.init(chartDom)
      const option = {
        title: {
          text: '歌曲评分分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['90+', '80-89', '70-79', '60-69', '60以下']
        },
        yAxis: {
          type: 'value',
          name: '数量'
        },
        series: [{
          name: '歌曲数量',
          type: 'bar',
          data: [5, 10, 3, 2, 0],
          barWidth: '30%', // 增加柱状图宽度
          itemStyle: {
            color: '#409EFF'
          }
        }]
      }
      myChart.setOption(option)
      // 响应式调整
      window.addEventListener('resize', function () {
        myChart.resize()
      })
    },
    initSecondBarChart () {
      const chartDom = document.getElementById('second-bar-chart')
      const myChart = echarts.init(chartDom)
      const option = {
        title: {
          text: '歌曲风格分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: ['流行', '摇滚', '爵士', '古典', '电子', '民谣']
        },
        yAxis: {
          type: 'value',
          name: '数量'
        },
        series: [{
          name: '风格数量',
          type: 'bar',
          data: [8, 5, 3, 2, 4, 3],
          barWidth: '30%', // 增加柱状图宽度
          itemStyle: {
            color: '#67C23A'
          }
        }]
      }
      myChart.setOption(option)
      // 响应式调整
      window.addEventListener('resize', function () {
        myChart.resize()
      })
    },
    async initDanceabilityChart () {
      const chartDom = document.getElementById('danceability-chart')
      const myChart = echarts.init(chartDom)
      try {
        const params = {
          start: this.startYear,
          end: this.endYear,
          genres: this.selectedStyles,
          keys: this.selectedKey
        }
        const danceData = await getDanceFenBu(params)
        const option = {
          title: {
            text: '歌曲适合跳舞程度分布',
            left: 'center',
            textStyle: {
              fontSize: 13
            }
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          xAxis: {
            type: 'category',
            data: ['0-0.1', '0.1-0.2', '0.2-0.3', '0.3-0.4', '0.4-0.5',
              '0.5-0.6', '0.6-0.7', '0.7-0.8', '0.8-0.9', '0.9-1.0'],
            axisLabel: {
              interval: 0,
              rotate: 45
            }
          },
          yAxis: {
            type: 'value',
            name: '歌曲数量'
          },
          series: [{
            name: '适合跳舞程度',
            type: 'bar',
            barWidth: '80%',
            data: danceData, // 使用API返回的数据
            itemStyle: {
              color: '#E6A23C'
            }
          }]
        }
        myChart.setOption(option)
        window.addEventListener('resize', function () {
          myChart.resize()
        })
      } catch (error) {
        console.error('获取跳舞程度数据失败:', error)
        ElMessage.error('获取跳舞程度数据失败')
      }
    },
    // 删除整个initPieChart方法
    // initPieChart () {
    //   const chartDom = document.getElementById('pie-chart-container')
    //   const myChart = echarts.init(chartDom)
    //   const option = {
    //     title: {
    //       text: '歌曲风格占比',
    //       left: 'center'
    //     },
    //     tooltip: {
    //       trigger: 'item'
    //     },
    //     legend: {
    //       orient: 'vertical',
    //       left: 'left'
    //     },
    //     series: [
    //       {
    //         name: '风格占比',
    //         type: 'pie',
    //         radius: '50%',
    //         data: [
    //           { value: 8, name: '流行' },
    //           { value: 5, name: '摇滚' },
    //           { value: 3, name: '爵士' },
    //           { value: 2, name: '古典' },
    //           { value: 4, name: '电子' },
    //           { value: 3, name: '民谣' }
    //         ],
    //         emphasis: {
    //           itemStyle: {
    //             shadowBlur: 10,
    //             shadowOffsetX: 0,
    //             shadowColor: 'rgba(0, 0, 0, 0.5)'
    //           }
    //         }
    //       }
    //     ]
    //   }
    //   myChart.setOption(option)
    //   // 响应式调整
    //   window.addEventListener('resize', function () {
    //     myChart.resize()
    //   })
    // },
    showSongDetail (song) {
      this.currentSong = song
      this.drawerVisible = true
    },
    async fetchGenres () {
      try {
        const response = await getGenresList()
        this.musicStyles = response // 假设API返回格式为[{name: "流行"},...]
        console.log('流派列表:', this.musicStyles)
      } catch (error) {
        console.error('获取流派列表失败:', error)
        ElMessage.error('获取流派列表失败')
      }
    },
    handleSizeChange (val) {
      this.pageSize = val
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.f() // 页码变化时调用f()更新数据
    },
    handleSearch () {
      if (!this.startYear || !this.endYear) {
        alert('请选择开始时间和结束时间') // 改为使用alert
        return
      }
      if (this.endYear < this.startYear) {
        alert('结束时间不能早于开始时间') // 改为使用alert
        return
      }
      this.currentPage = 1
      this.f()
      this.initKeyPieChart()
      this.initStylePieChart()
      this.initDanceabilityChart()
      this.initEnergyChart()
    },
    async f () {
      try {
        const params = {
          start: this.startYear,
          end: this.endYear,
          genres: this.selectedStyles,
          keys: this.selectedKey,
          page: this.currentPage,
          pageSize: this.pageSize
        }
        const response = await getList(params) // 直接使用导入的方法
        this.tableData = response.list
        this.total = response.total
      } catch (error) {
      }
    },
    async fetchDiaoShi () {
      try {
        const response = await getDiaoShi()
        // 调式名称映射
        const keyNames = {
          0: 'C',
          1: 'C#',
          2: 'D',
          3: 'D#',
          4: 'E',
          5: 'F',
          6: 'F#',
          7: 'G',
          8: 'G#',
          9: 'A',
          10: 'A#',
          11: 'B'
        }
        this.keyOptions = [
          ...response.map(item => ({
            value: item,
            label: keyNames[item] || item // 如果没有匹配则显示原值
          }))
        ]
        console.log('调式列表:', this.keyOptions)
      } catch (error) {
        console.error('获取调式列表失败:', error)
        alert('获取调式列表失败')
      }
    }
  },

  data () {
    return {
      isLoading: {
        keyChart: false,
        styleChart: false,
        danceChart: false,
        energyChart: false
      },
      drawerVisible: false,
      currentSong: null,
      tableData: [],
      currentPage: 1, // 当前页码
      pageSize: 16, // 修改为每页显示1条
      total: 0, // 总条数
      loginForm: {
        account: '',
        password: ''
      },
      showRegisterDialog: false,
      customerForm: {
        account: '',
        username: '',
        company: '',
        phone: '',
        password: ''
      },
      startTime: '',
      endTime: '',
      startYear: '',
      endYear: '',
      yearOptions: (() => {
        const years = []
        for (let i = 2023; i >= 2000; i--) {
          years.push(i)
        }
        return years
      })(), // 这里添加逗号
      selectedStyles: [],
      musicStyles: [
        '流行', '摇滚', '爵士', '古典',
        '电子', '民谣', 'hithop', 'R&B'
      ],
      selectedKey: [], // 改为数组类型，支持多选
      keyOptions: [
        { value: -1, label: '无' },
        { value: 0, label: 'C' },
        { value: 1, label: 'C#' },
        { value: 2, label: 'D' },
        { value: 3, label: 'D#' },
        { value: 4, label: 'E' },
        { value: 5, label: 'F' },
        { value: 6, label: 'F#' },
        { value: 7, label: 'G' },
        { value: 8, label: 'G#' },
        { value: 9, label: 'A' },
        { value: 10, label: 'A#' },
        { value: 11, label: 'B' }
      ]
    }
  },
  watch: {
    showRegisterDialog (newVal) {
      if (!newVal) {
        this.customerForm = {
          account: '',
          name: '',
          company: '',
          phone: '',
          password: ''
        }
      }
    }
  }
}
</script>

<style scoped>
.login-card {
  width: 400px;
  padding: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}

/* 菜单样式 */
.el-menu {
  width: 100vw;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1000;
}
.song-detail-dialog {
  width: 400px;
}
.song-detail-drawer {
      --el-drawer-padding-primary: 20px;
      --el-drawer-bg-color: #f8f9fa;
    }
    .song-detail-container {
      padding: 20px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    }
    .detail-header {
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid #ebeef5;
    }
    .detail-header h3 {
      color: #303133;
      font-size: 18px;
      margin: 0;
    }
    .detail-row {
      display: flex;
      margin-bottom: 15px;
      align-items: center;
      padding: 8px 12px;
      border-radius: 4px;
      transition: background-color 0.3s;
    }
    .detail-row:hover {
      background-color: #f5f7fa;
    }
    .detail-label {
      color: #909399;
      width: 120px;
      font-weight: bold;
      font-size: 14px;
    }
    .detail-value {
      color: #606266;
      flex: 1;
      font-size: 14px;
    }
      /* 确保drawer不影响其他组件布局 */
      .custom-drawer {
      position: fixed;
      z-index: 1001; /* 适当设置z-index */
      box-shadow: 0 0 15px rgba(0,0,0,0.1);
    }
    .custom-drawer-modal {
      background-color: rgba(0,0,0,0.3);
    }
    /* 确保页面主体内容不会被drawer挤压 */
    .main-content {
      transition: none !important;
      margin-left: 0 !important;
    }
</style>
